<template>
  <div class="login-container">
    <h2>用户登录</h2>
    <form @submit.prevent="handleLogin">
      <div class="form-group">
        <label>用户名</label>
        <input
            v-model="username"
            type="text"
            required
            placeholder="请输入用户名"
        >
      </div>
      <div class="form-group">
        <label>密码</label>
        <input
            v-model="password"
            type="password"
            required
            placeholder="请输入密码"
        >
      </div>
      <button type="submit" class="login-btn">登录</button>
      <p v-if="errorMsg" class="error">{{ errorMsg }}</p>
    </form>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '@/stores/userStore';

const username = ref('');
const password = ref('');
const errorMsg = ref('');
const router = useRouter();
const userStore = useUserStore();

const handleLogin = async () => {
  try {
    const success = await userStore.login(username.value, password.value);
    if (success) {
      router.push('/'); // 登录成功跳转首页
    } else {
      errorMsg.value = '用户名或密码错误';
    }
  } catch (err) {
    errorMsg.value = '登录失败，请重试';
  }
};
</script>
